package com.wl.dzt.sys.ui.ext;

import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.controller.result.FormResult;
import com.wl.dzt.sys.controller.result.TableResult;
import com.wl.dzt.sys.core.dao.JDao;
import com.wl.dzt.sys.core.dao.select.Select;
import com.wl.dzt.sys.util.WebUtils;
import com.wl.dzt.sys.util.json.Json;
import org.springframework.cglib.beans.BeanMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wl_code@163.com
 * @date 2018/7/5/005
 * @version 1.0
 * @description ext模板
 * 用于封装一些常用的ext交互
 *
 */
public class ExtTemplate {

    /**
     * <b>列表模板</b>
     * <p>
     * extjs所需列表数据
     * </p>
     *
     * @param data
     * @param response
     */
    public static void gridTemplate(List<?> data, Integer count, HttpServletResponse response) {
        String json = Json.parse(Ext.extGrid(data, count));
        WebUtils.print(json, response);
    }

    /**
     * <b>列表模板</b>
     * <p>
     * extjs所需列表数据
     * </p>
     *
     * @param request
     * @param response
     */
    public static void gridTemplate(HttpServletRequest request, HttpServletResponse response, JDao dao) {
        Param param = WebUtils.getParam(request);
        Select select = param.toSelect();
        String json = Json.parse(Ext.extGrid(dao.list(select), dao.count(select)));
        WebUtils.print(json, response);
        WebUtils.print("", response);
    }

    /**
     * <b>列表模板</b>
     * <p>
     * extjs所需列表数据
     * </p>
     *
     * @param tableResult
     * @param response
     */
    public static void gridTemplate(TableResult tableResult, HttpServletResponse response) {
        String json = Json.parse(Ext.extGrid(tableResult.getData(), tableResult.getCount()));
        WebUtils.print(json, response);
    }

    /**
     * <b>表单模板</b>
     * <p>
     * extjs所需表单模板
     * </p>
     *
     * @param formResult
     * @param response
     */
    public static void formTemplate(FormResult formResult, HttpServletResponse response) {
        WebUtils.print(Json.parse(formResult), response);
    }

    /**
     * <b>加载模板</b>
     * <p>
     * extjs所需加载模板
     * </p>
     *
     * @param request
     * @param response
     */
    public static void loadTemplate(Object entity, Map<String, Object> expansions, HttpServletRequest request,
                                    HttpServletResponse response) {
        if (expansions == null) {
            expansions = new HashMap<>();
        }
        BeanMap map = BeanMap.create(entity);
        expansions.putAll(map);
        WebUtils.print(Json.parse(Ext.extLoad(expansions)), response);

    }

    /**
     * <b>树形加载模板</b>

     *
     * @param data
     * @param response
     */
    public static void treeTemplate(List<Map<String, Object>> data, HttpServletResponse response) {
        WebUtils.print(Json.parse(data), response);
    }
}
